#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
将font_meta.py转换为Java类的脚本
"""

import re
import os
from pypinyin import lazy_pinyin, Style

def chinese_to_pinyin(chinese_str):
    """
    将中文转换为拼音，使用下划线分隔
    """
    # 使用pypinyin库将中文转换为拼音
    pinyin_list = lazy_pinyin(chinese_str, style=Style.NORMAL)
    # 将拼音列表连接成字符串，用下划线分隔，并转换为大写
    return '_'.join(pinyin_list).upper()

def convert_font_name_to_constant(font_name):
    """
    将字体名称转换为Java常量名
    """
    # 处理中文字符，转换为拼音
    if any('\u4e00' <= char <= '\u9fff' for char in font_name):
        return chinese_to_pinyin(font_name)
    
    # 处理英文字符和特殊字符
    # 将空格和连字符替换为下划线
    constant_name = re.sub(r'[-\s]+', '_', font_name)
    # 将驼峰命名转换为下划线（在小写字母后跟大写字母的位置插入下划线）
    constant_name = re.sub(r'([a-z0-9])([A-Z])', r'\1_\2', constant_name)
    # 转换为大写
    return constant_name.upper()

def parse_font_meta_file(file_path):
    """
    解析font_meta.py文件，提取字体信息
    """
    fonts = []
    with open(file_path, 'r', encoding='utf-8') as f:
        content = f.read()
        
    # 使用正则表达式匹配字体定义行
    # 匹配格式: 标识符 = Effect_meta("名称", VIP标志, "资源ID", "效果ID", "MD5")
    pattern = r'(\w+)\s*=\s*Effect_meta\("([^"]+)",\s*(True|False),\s*"([^"]+)",\s*"([^"]+)",\s*"([^"]+)"\)'
    matches = re.findall(pattern, content)
    
    for match in matches:
        identifier, name, is_vip, resource_id, effect_id, md5 = match
        constant_name = convert_font_name_to_constant(name)
        fonts.append({
            'original_name': name,
            'identifier': identifier,
            'constant_name': constant_name,
            'is_vip': is_vip,
            'resource_id': resource_id,
            'effect_id': effect_id,
            'md5': md5
        })
    
    return fonts

def generate_java_class(fonts, output_file):
    """
    生成Java类文件
    """
    java_content = '''package com.cms.jy.draft.constant;

import com.cms.jy.draft.entity.Effect;

/**
 * 字体常量类
 * 由generate_font_java.py脚本自动生成
 */
public class Font {
    
'''
    
    # 为每个字体生成静态常量
    for font in fonts:
        java_content += f'    /**\n'
        java_content += f'     * {font["original_name"]}\n'
        java_content += f'     */\n'
        java_content += f'    public static final Effect {font["constant_name"]} = '
        java_content += f'new Effect("{font["original_name"]}", {font["is_vip"]}, '
        java_content += f'"{font["resource_id"]}", "{font["effect_id"]}", "{font["md5"]}");\n\n'
    
    java_content += '}\n'
    
    # 写入文件
    with open(output_file, 'w', encoding='utf-8') as f:
        f.write(java_content)
    
    print(f"Java类已生成: {output_file}")

def main():
    # 定义文件路径
    font_meta_path = 'src/main/java/com/cms/jy/draft/constant/font_meta.py'
    output_java_path = 'src/main/java/com/cms/jy/draft/constant/FontConstants.java'
    
    # 检查输入文件是否存在
    if not os.path.exists(font_meta_path):
        print(f"错误: 找不到文件 {font_meta_path}")
        return
    
    # 解析字体元数据
    print("正在解析font_meta.py...")
    fonts = parse_font_meta_file(font_meta_path)
    print(f"找到 {len(fonts)} 个字体定义")
    
    # 生成Java类
    print("正在生成Java类...")
    generate_java_class(fonts, output_java_path)
    print("完成!")

if __name__ == '__main__':
    main()